<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48" @keyup.enter.native="searchList">
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="搜索名称">
                <a-input v-model="queryParam.keyWord" placeholder="请输入活动名称或标记名称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="活动状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="1">未开始</a-select-option>
                  <a-select-option :value="2">进行中</a-select-option>
                  <a-select-option :value="3">已结束</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="活动场景">
                <a-select v-model="queryParam.triggerCondition" placeholder="请选择" default-value="null" :getPopupContainer="triggerNode => triggerNode.parentNode">
                  <a-select-option value="">不限</a-select-option>
                  <a-select-option :value="item.code" v-for="(item, index) in sceneList" :key="index">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xxl="6" :lg="8" :md="12" :sm="24">
              <a-form-item label="活动日期">
                <a-range-picker
                  style="width: 100%"
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  format="YYYY-MM-DD HH:mm:ss"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryParam.timePicker"
                />
              </a-form-item>
              <!-- :show-time="{ defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('11:59:59', 'HH:mm:ss')] }" -->
            </a-col>
            <a-col :xxl="24" :lg="16" :md="24" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="searchList">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetList">重置</a-button>
                <a-button style="margin-left: 8px" type="primary" icon="plus" @click="openAddModal">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table ref="table" size="default" :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1500 }">
        <span slot="status" slot-scope="text">{{ text | status }}</span>
        <span slot="rewardTypes" slot-scope="text">{{ rewardTypes(text) }}</span>
        <span slot="triggerCondition" slot-scope="text">{{ triggerCondition(text) }}</span>
        <span slot="actTime" slot-scope="text, record">
          <span v-if="record.validityType == 1">{{ record.startTime }} ~ {{ record.endTime }}</span>
          <span v-else>-</span>
        </span>
        <span slot="action" slot-scope="text, record">
          <!-- <a-button type="link" class="action-btn" :disabled="record.status == 3 || record.activityType != 1" @click="handlePickle(record)">投放</a-button> 
          <a-divider type="vertical" /> -->
          <router-link :to="`/box/operations/marketing-activity/detail-list/${record.id}`">明细</router-link>
          <a-divider type="vertical" />
          <!-- <a-button type="link" class="action-btn" disabled v-if="record.status == 3">编辑</a-button>
          <a @click="handleEdit(`/box/operations/marketing-activity/activity-edit/${record.triggerCondition}/${record.id}`)" v-else>编辑</a>
          <a-divider type="vertical" />
          <a @click="handleEdit(`/box/operations/marketing-activity/activity-edit/copy/${record.id}`)">复制</a>
          <a-divider type="vertical" />
          <a-popconfirm title="确定下架吗?" ok-text="Yes" cancel-text="No" @confirm="handleEnable(record)" v-if="record.status == 2">
            <a href="#">下架</a>
          </a-popconfirm>
          <a-button type="link" class="action-btn" disabled v-else>下架</a-button>
          <a-divider type="vertical" />
          <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(record)" v-if="record.status != 2">
            <a href="#">删除</a>
          </a-popconfirm>
          <a-button type="link" class="action-btn" disabled v-else>删除</a-button> -->
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item :disabled="record.status == 3 || record.activityType != 1" @click="handlePickle(record)">
                投放
              </a-menu-item>
              <a-menu-item :disabled="record.status != 1" @click="handleEdit(`/box/operations/marketing-activity/activity-edit/${record.triggerCondition}/${record.id}`)">
                编辑
              </a-menu-item>
              <a-menu-item :disabled="record.status == 1" @click="handleEdit(`/box/operations/marketing-activity/activity-edit/${record.triggerCondition}/${record.id}`)">
                查看
              </a-menu-item>
              <a-menu-item @click="handleEdit(`/box/operations/marketing-activity/activity-edit/copy/${record.id}`)">
                复制
              </a-menu-item>
              <a-menu-item :disabled="record.status != 2" @click="handleEnable(record)">下架</a-menu-item>
              <a-menu-item :disabled="record.status == 2" @click="handleDelete(record)">删除</a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </s-table>
    </a-card>
    <AddModal ref="addModal" :sceneList="sceneList"></AddModal>
    <CodeModal ref="codeModal"></CodeModal>
  </div>
</template>
<script>
import { listMixin } from '@/views/box/util/listMixin'
import { routeMixin } from '@/views/box/util/routeMixin'
import { initDictFromBox } from '@/views/box/util/global'
import { marketingActivityList, marketingActivityDelete, marketingActivityDisable, marketingActivityPickle } from '@/api/box/marketing'
import moment from 'moment'
import 'moment/locale/zh-cn'
import AddModal from './components/addModal.vue'
import CodeModal from '@/views/box/components/SpreadModal/codeModal'
const columns = [
  { title: 'ID', dataIndex: 'id', align: 'center', width: 130, fixed: 'left' },
  { title: '活动场景', dataIndex: 'triggerCondition', align: 'center', scopedSlots: { customRender: 'triggerCondition' } },
  { title: '活动名称', dataIndex: 'activityName', align: 'center' },
  { title: '有效期类型', dataIndex: 'validityType', align: 'center', customRender: text => (text == 1 ? '指定时间' : '长期有效') },
  { title: '活动时间', align: 'center', scopedSlots: { customRender: 'actTime' }, width: 200 },
  { title: '活动状态', dataIndex: 'status', align: 'center', scopedSlots: { customRender: 'status' } },
  { title: '活动类型', dataIndex: 'activityType', align: 'center', customRender: text => (text == 1 ? '推广活动' : '常规活动') },
  { title: '奖励类型', dataIndex: 'rewardTypes', align: 'center', scopedSlots: { customRender: 'rewardTypes' } },
  { title: '标记名称', dataIndex: 'flagName', align: 'center', customRender: (text, record) => (text && record.isFlag == 1 ? text : '-') },
  { title: '操作', fixed: 'right', align: 'center', scopedSlots: { customRender: 'action' }, width: 120 }
]
let activityStatus = ['未开始', '进行中', '已结束']
export default {
  mixins: [listMixin, routeMixin],
  data() {
    return {
      columns,
      sceneList: [],
      // 查询条件参数
      queryParam: {
        status: '',
        triggerCondition: ''
      }
    }
  },
  components: { AddModal, CodeModal },
  filters: {
    status(v) {
      return activityStatus[parseInt(v) - 1]
    }
  },
  computed: {
    loadData() {
      return parameter => {
        // 加载数据方法 必须为 Promise 对象
        return this.fetchData(parameter)
      }
    },
    rewardTypes() {
      return text => {
        let arr = []
        if (text.indexOf(1) > -1) {
          arr.push('优惠券')
        }
        if (text.indexOf(2) > -1) {
          arr.push('实物')
        }
        return arr.join(',')
      }
    },
    triggerCondition() {
      return text => {
        let result = this.sceneList.filter(e => e.code == text)
        if (result.length > 0) {
          return result[0].name
        } else {
          return text
        }
      }
    }
  },
  watch: {
    $route(to, from) {
      let currentPath = '/box/operations/marketing-activity/list'
      let editPath = '/box/operations/marketing-activity/activity-edit'
      let detailPath = '/box/operations/marketing-activity/detail-list'
      if (from.path.includes(editPath) && to.path.includes(currentPath)) {
        console.log('***********refresh***********')
        this.$refs.table.refresh() // 来自会员详情刷新当前列表
      } else if ((from.path.includes(currentPath) && to.path.includes(detailPath)) || to.path.includes(editPath)) {
        // console.log('***********keep***********')
      } else {
        if (from.path.includes(currentPath) && !to.path.includes('/box/operations/marketing-activity')) {
          console.log('***********destroy***********')
          this.$destroy()
          /*  console.log('***********reset***********')
          this.queryParam = {
            status: '',
            triggerCondition: ''
          }
          this.$refs.table.refresh(true) */
        }
      }
    }
  },
  created() {
    this.getScenceList()
  },
  deactivated() {},
  methods: {
    moment,
    fetchData(parameter) {
      let formValue = this.filterFields(this.queryParam)
      let params = {
        page: parameter,
        requestData: formValue
      }
      try {
        return this.fetchList(params, marketingActivityList).then(res => {
          if (res.code == 0) {
            return res
          } else {
            this.$message.warning(res.msg)
            return {
              data: [],
              page: {
                pageNo: 1,
                pageSize: 10,
                count: 0
              }
            }
          }
        })
      } catch (err) {
        console.log(err.response)
      }
    },
    filterFields(values) {
      const formValue = {}
      Object.keys(values).forEach(i => {
        if (values[i] !== '' && values[i] !== undefined && values[i] !== null) {
          if (i == 'timePicker') {
            formValue.startTime = values[i][0].format('YYYY-MM-DD HH:mm:ss')
            formValue.endTime = values[i][1].format('YYYY-MM-DD HH:mm:ss')
          } else {
            formValue[i] = values[i]
          }
        }
      })
      return formValue
    },
    resetList() {
      this.queryParam = {
        status: '',
        triggerCondition: ''
      }
      this.$refs.table.refresh(true)
    },
    getScenceList() {
      if (this.sceneList.length > 0) return
      initDictFromBox('marketing_scene').then(res => {
        // console.log(res)
        this.sceneList = res
      })
    },
    openAddModal() {
      this.$refs.addModal.show()
    },
    handleEnable(record) {
      let that = this
      this.$confirm({
        title: `确认下架 ${record.activityName} 吗？`,
        // content: h => <div style="color:red;">Some descriptions</div>,
        onOk() {
          let params = {
            requestData: {
              id: record.id
            }
          }
          marketingActivityDisable(params).then(res => {
            if (res.code == 0) {
              that.$message.success('下架成功')
              that.$refs.table.refresh()
            } else {
              that.$message.warning(res.msg)
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    handleDelete(record) {
      let that = this
      this.$confirm({
        title: `确定删除 ${record.activityName} 吗？`,
        // content: h => <div style="color:red;">Some descriptions</div>,
        onOk() {
          let params = {
            requestData: {
              id: record.id
            }
          }
          marketingActivityDelete(params).then(res => {
            if (res.code == 0) {
              that.$message.success('删除成功')
              that.$refs.table.refresh()
            } else {
              that.$message.warning(res.msg)
            }
          })
        },
        onCancel() {
          console.log('Cancel')
        },
        class: 'test'
      })
    },
    handlePickle(record) {
      let params = {
        requestData: {
          id: record.id
        }
      }
      marketingActivityPickle(params).then(res => {
        if (res.code == 0) {
          let codeData = {
            codeUrl: res.data.codeUrl,
            qrcodeUrl: res.data.qrcodeUrl,
            path: res.data.path,
            code: res.data.code
          }
          this.$refs.codeModal.show(codeData)
        } else {
          this.$message.warning(res.msg)
        }
      })
      /* let codeData = {
        codeUrl: record.codeUrl,
        qrcodeUrl: record.qrcodeUrl,
        path: record.path,
        code: record.code
      }
      this.$refs.codeModal.show(codeData) */
    }
  }
}
</script>
<style lang="less" scoped>
.action-btn {
  padding: 0;
}
</style>

